package com.xdclass.thread.hang;

/**
 * @Author: Timo
 * @Date: 2019/4/26 10:51
 * @Description: 模拟死锁的状态
 */
public class DeadDemo implements Runnable{

    private static Object object = new Object();

    @Override
    public void run() {
        synchronized (object) {
            // 持有资源
            System.out.println(Thread.currentThread().getName()+"占用资源");
            Thread.currentThread().suspend();
        }
        System.out.println(Thread.currentThread().getName()+"释放资源");
    }



    public static void main(String[] args) throws InterruptedException {
       test_1();

    }

    /**
     * 这里的案例会正常输出：
     * T_1占用资源
     * T_1释放资源
     * T_2占用资源
     * T_2释放资源
     * 因为当T_1线程挂起的时候休眠3s之后就会被唤醒，然后T_2占用资源之后就会被挂起，3s过后就会被唤醒
     * @throws InterruptedException
     */
    public static void test_1() throws InterruptedException {
        Thread t1 = new Thread(new DeadDemo());
        t1.setName("T_1");
        t1.start();
        Thread.sleep(3000L);
        t1.resume();

        Thread t2 = new Thread(new DeadDemo());
        t2.setName("T_2");
        t2.start();
        Thread.sleep(3000L);
        t2.resume();
    }

    /**
     * 这里的案例会正常输出：
     * T_1占用资源
     * T_1释放资源
     * T_2占用资源
     * 因为当T_1线程挂起当前线程休眠1s之后就会被唤醒，然后由于时间过快的原因，T_2就会直接唤醒当前线程，但是当前线程还没有挂起当前线程，就直接被唤醒了，这时候线程才被挂起，就会出现当前线程会一直是挂起的状态。
     * @throws InterruptedException
     */
    public static void test_2() throws InterruptedException {
        Thread t1 = new Thread(new DeadDemo(),"T_1");
        t1.start();
        Thread.sleep(1000L);
        t1.resume();

        Thread t2 = new Thread(new DeadDemo(),"T_2");
        t2.start();
        t2.resume();
    }
}
